package com.py.gs.tools;

import java.util.TimeZone;

/**
 * 高效的时间工具集
 * @modifyBy KXZ
 * 2017年12月13日
 */
public class PYTimeTools {
	
	public static int TIME_ZONE_DIFF = TimeZone.getDefault().getRawOffset()/1000;
	public final static int DAY_SECONDS = 86400;
	public final static int HOUR_SECONDS = 3600;
	public final static int DAY_MILLIS = DAY_SECONDS * 1000;
	public final static int HOUR_MILLIS = HOUR_SECONDS * 1000;
	
	/** 通过当前毫秒数获取1970年至今的天数 */
	public static int getDays1970(long timeMillis){
		return (int) ((timeMillis/1000+TIME_ZONE_DIFF)/DAY_SECONDS);
	}
	
	/** 通过当前秒数获取1970年至今的天数 */
	public static int getDays1970(int timeSeconds){
		return (timeSeconds+TIME_ZONE_DIFF)/DAY_SECONDS;
	}
	
	/** 获取从1970年+days1970天数当天的0点秒数 */
	public static int getZeroSeconds(int days1970){
		return days1970*DAY_SECONDS-TIME_ZONE_DIFF;
	}
	
	static ThreadLocal<Long> currentTime = new ThreadLocal<>();
	
	/**
	 * 获取当前业务开始时的1970-01-01 00:00:00到当前的秒数
	 * 避免业务处理时跳秒导致的前后时间不一致bug
	 * 业务处理开始时,一定要先调用resetCurrentSecond(),才能取到实时的秒数
	 */
	public static int currentSecond() {
		Long now = currentTime.get();
		if(now == null) {
			return (int) (resetCurrentTime()/1000);
			//throw new RuntimeException("业务处理开始时没有调用resetCurrentSecond()");
		}
		return (int)(long)(now/1000);
	}
	
	/** 业务开始时重置 */
	public static long resetCurrentTime() {
		long now = System.currentTimeMillis();
		currentTime.set(now);
		return now;
	}
	
	/**
	 * 获取当前业务开始时的1970-01-01 00:00:00到当前的毫秒数
	 */
	public static long currentTimeMillis() {
		Long now = currentTime.get();
		if(now == null) {
			return resetCurrentTime();
			//throw new RuntimeException("业务处理开始时没有调用resetCurrentSecond()");
		}
		return now;
	}
	
	public static int getDayBeginTimestamp() {
		int secs = currentSecond();
		return secs-((secs+TIME_ZONE_DIFF)%DAY_SECONDS);
	}
	
	/**
	 * 获取指定时间戳的当天开始时间
	 * @param timeSeconds
	 * @return
	 */
	public static int getDayBeginTimestamp(int timeSeconds) {
		return timeSeconds-((timeSeconds+TIME_ZONE_DIFF)%DAY_SECONDS);
	}
	
	/**
	 * 获取本周一0点的时间戳
	 * 注意:周一到周日为一周循环,如果今天是周日,那么获取到的是6天前周一0点的秒数
	 */
	public static int getWeekBeginTimestamp() {
		int secs = currentSecond();
		return secs-((secs+TIME_ZONE_DIFF)%DAY_SECONDS) - ((getDays1970(secs)+3)%7)*DAY_SECONDS;//0星期1...6星期日
	}
	
	/**
	 * 获取6天前0点时间戳
	 */
	public static int getSixDaysAgoTimestamp() {
		return getDayBeginTimestamp() - 6 * DAY_SECONDS;
	}
	
	/**
	 * 获取今日剩余时间秒数
	 * add by linm on 20181009
	 */
	public static int getTodayLeftSeconds() {
		return getDayBeginTimestamp() + PYTimeTools.DAY_SECONDS - currentSecond();
	}
}
